#!/bin/bash

INIT_FILE="/app/initialized"
echo "检查初始化文件: $INIT_FILE"

if [ ! -f "$INIT_FILE" ]; then
    echo "未初始化，开始初始化过程..."
    flask db init && echo "db init 成功" || echo "db init 失败"
    flask db migrate -m "Initial migration" && echo "db migrate 成功" || echo "db migrate 失败"
    flask db upgrade && echo "db upgrade 成功" || echo "db upgrade 失败"

    # 创建初始角色和用户
    flask create-init-role && echo "创建初始角色成功" || echo "创建初始角色失败"
    flask create-init-department && echo "创建初始部门成功" || echo "创建初始部门失败"
    flask create-init-user && echo "创建初始用户成功" || echo "创建初始用户失败"
    flask create-init-financial && echo "创建初始财务成功" || echo "创建初始财务失败"

    touch "$INIT_FILE" && echo "初始化标记文件创建成功" || echo "初始化标记文件创建失败"
else
    echo "已初始化，执行常规迁移..."
    flask db migrate -m "Auto migration"
    flask db upgrade
fi


flask routes

exec gunicorn -b:5000  --workers 9 --access-logfile - --error-logfile - run:app